package com.itlzh.mall.common.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itlzh.mall.common.enums.ResponseEnum;
import com.itlzh.mall.common.result.Result;
import com.itlzh.mall.common.utils.JwtUtils;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class AuthorizationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = request.getHeader("Authorization");
        //如果token为空，用户未登录。否则，如果token过期，登录过期，否则通过拦截并存储用户信息
        if(token==null){
            //将response输出转换为json格式
            ObjectMapper objectMapper = new ObjectMapper();
            response.setContentType("application/json;charset=utf-8");
            objectMapper.writeValue(response.getWriter(), Result.fail(ResponseEnum.USER_NOT_LOGGED_IN));
            return false;
        } else if (JwtUtils.isExpired(token)) {
            response.setContentType("application/json;charset=utf-8");
            new ObjectMapper().writeValue(response.getWriter(), Result.fail(ResponseEnum.PERMISSION_TOKEN_EXPERED));
            return false;
        }else{
            //TODO 使用ThreadLocal  存储用户信息
            Long id=  JwtUtils.parseToken(token).get("userId", Long.class);
            return true;
        }
    }
}
